//  This product includes software developed by Denim Group, Ltd. (http://www.denimgroup.com/)
//  All use and distribution of the Denim Group developed software is subject to Version 2.0
//  of the Apache License (http://www.apache.org/licenses/LICENSE-2.0).

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.Diagnostics;

using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;

namespace AppScan.DefectLogger
{
    public partial class ConnectionForm : UserControl
    {
		private DataGridView _fieldsGridView;
		private DefectLoggerBase _extension;
		private bool _loadingConfig = false;

        public ConnectionForm()
        {
            InitializeComponent();
        }

		public void Init(DataGridView fields, DefectLoggerBase extension)
		{
			_fieldsGridView = fields;
			_extension = extension;

			Version version = Assembly.GetExecutingAssembly().GetName().Version;
			lblVersion.Text = "1.0";
		}

        private void RefreshBtn_Click(object sender, EventArgs e)
        {
            // Make sure we have a username (allow blank password)
            if (string.IsNullOrEmpty(UserTB.Text))
            {
                MessageBox.Show("Please enter username");
                return;
            }

            try
            {
				// login
				_extension.DefectTrackingSystem.Login(ServerUrlTB.Text,
													UserTB.Text,
													PasswordTB.Text,
													DomainTB.Text,
													ProjectDropDown.SelectedItem.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error loading domains: " + ex.Message);
                Console.Out.Write(ex);
            }
        }

		public void SetConfig(DefectSystemConfig config)
		{
			_loadingConfig = true;
			ServerUrlTB.Text = config.ServerUrl;
			UserTB.Text = config.UserName;
			PasswordTB.Text = config.Password;

			if (config.DomainName.Length > 0)
			{
                DomainTB.Text = config.DomainName;
			}

			if (config.ProjectName.Length > 0)
			{
				ProjectDropDown.Items.Clear();
				ProjectDropDown.Items.Add(config.ProjectName);
				ProjectDropDown.SelectedItem = config.ProjectName;
			}
			_loadingConfig = false;
		}

		public void GetConfig(DefectSystemConfig config)
		{
			config.ServerUrl = ServerUrlTB.Text;
			config.UserName = UserTB.Text;
			config.Password = PasswordTB.Text;
            config.DomainName = DomainTB.Text;
			if (ProjectDropDown.SelectedItem != null)
				config.ProjectName = ProjectDropDown.SelectedItem.ToString();
		}

		private void LoadFieldsBtn_Click(object sender, EventArgs e)
		{

		}

		private void DomainDropDown_SelectedIndexChanged(object sender, EventArgs e)
		{

		}

		private void btnConnect_Click(object sender, EventArgs e)
		{
			// Make sure we have a URL
			if (string.IsNullOrEmpty(ServerUrlTB.Text))
			{
				MessageBox.Show("Please enter a Team Foundation Server URL");
				return;
			}


			TFS tfs = _extension.DefectTrackingSystem as TFS;

            // Make sure we have a username (allow blank password)
            if (string.IsNullOrEmpty(UserTB.Text))
            {
                MessageBox.Show("Please enter username");
                return;
            }

            try
            {
                // login

                //  Shouldn't display password on screen :)
                // MessageBox.Show("About to log in with serverURL: " + ServerUrlTB.Text + ", username: " + UserTB.Text + ", password: " + PasswordTB.Text + ", domain: " + DomainTB.Text);

                _extension.DefectTrackingSystem.Login(ServerUrlTB.Text,
                                                    UserTB.Text,
                                                    PasswordTB.Text,
                                                    DomainTB.Text,
                                                    string.Empty);  //  No project known at this point
            }
            catch (Exception ex)
            {
                MessageBox.Show("Login failed: " + ex.Message);
                Console.Out.Write(ex);
                return;
            }

            TeamFoundationServer conn;
            conn = tfs.Conn;

            if (conn == null)
            {
                MessageBox.Show("Unable to establish connection.");
                return;
            }

            try
            {
                // MessageBox.Show("About to load projects.  Conn is: " + conn.ToString());

                // Clear old items
                ProjectDropDown.Items.Clear();

                WorkItemStore store = new WorkItemStore(conn);

                ProjectCollection projectsList = store.Projects;
                for (int i = 0; i < projectsList.Count; i++)
                {
                    // MessageBox.Show("Project: " + projectsList[i].Name + " with ID: " + projectsList[i].Id);
                    ProjectDropDown.Items.Add(projectsList[i].Name);
                }

                ProjectDropDown.SelectedIndex = 0;

            }
            catch (Exception ex)
            {
                MessageBox.Show("Error loading projects: " + ex.Message);
                Console.Out.Write(ex);
            }
		}

		private void mailLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
		{
            //removed on version 2.0
		}


        private String[] GetFieldValues(string fieldName, string listName, TeamFoundationServer conn)
		{
            /*  TODO - Link up with custom Team Foundation Server work item fields
			try
			{    
				Customization cust = (Customization)conn.Customization;
				CustomizationFields custFields = (CustomizationFields)cust.Fields;
				if (!custFields.get_FieldExists("BUG", fieldName))
				{
					return null; ;
				}

				CustomizationField custField = (CustomizationField)custFields.get_Field("BUG", fieldName);
				CustomizationList list = (CustomizationList)custField.List;
				CustomizationListNode node = (CustomizationListNode)list.RootNode;
				List vals = node.Children;
				string[] values = new string[node.ChildrenCount];
				for (int i = 1; i <= vals.Count; i++)
				{
					CustomizationListNode childNode = (CustomizationListNode)vals[i];
					values[i - 1] = childNode.Name;
				}
				return values;
			}
			catch (Exception)
			{
				return null;
			}
             */
            return(null);
		}
    }
}
